const { rmSync } = require('fs')
const path = require('path')
const db = require('../db/index')

//发布新文章
exports.addArticle = (req,res) => {
  //手动判断是否上传了文章封面
  if(!req.file || req.file.filename !== 'cover_img')
    return res.cc('文章封面是必选参数！')

  const articleInfo = {
    //标题、内容、状态、所属类的id
    ...req.body,
    //文章封面在服务端的存放路径
    cover_img:path.join('/uploads',req.file.filename),
    //文章发布时间
    pub_date:new Date(),
    //文章作者的id
    author_id:req.user.id
  }

  const sql = 'insert into ev_articles set ?'
  db.query(sql,articleInfo,(err,results) => {
    if(err) return res.cc(err)
    if(results.affectedRows !== 1) return res.cc('发布文章失败！')

    res.cc('发布文章成功',0)
  })
}

//获得所有文章
exports.getAllArticle = (req,res) => {
  const sql = 'select * from ev_articles where is_delete=0 order by id asc'
  db.query(sql,(err,results) => {
    if(err) return res.cc(err)
    res.send({
      status:0,
      message:"获取所有文章成功！",
      data:results
    })
  })
}